<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="1000"
    show-footer
    show-zoom
    resize
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close"
    :z-index="2000"
  >
    <template #default>
      <el-tabs v-model="activeName" type="card" @tab-change="changeTab">
        <el-tab-pane label="图片任务详情" :name="1">
          <el-card class="mb-2" shadow="never">
            <span class="pictureTitle">商品详情</span>
            <vxe-table ref="tableRef" :data="form.images_assignment_sku">
              <vxe-column type="seq" width="60" title="序号"></vxe-column>
              <vxe-column title="SPU">
                <template #default="{ row }">
                  <div>
                    <div>{{ row.goods_sku?.spu }}</div>
                  </div>
                </template>
              </vxe-column>
              <vxe-column title="SKU/自定义SKU">
                <template #default="{ row }">
                  <div>
                    <span>{{ row.goods_sku?.sku }}</span>
                    <span class="block">自定义: {{ row.goods_sku?.custom_sku }}</span>
                  </div>
                </template>
              </vxe-column>
              <template v-if="arrAttributeList.length > 0">
                <vxe-column
                  width="100"
                  :title="item.name"
                  v-for="(item, index) in arrAttributeList"
                  :key="index"
                >
                  <template #default="{ row }">
                    {{ row.goods_sku.sku_specification.attributes[item.key] }}
                  </template>
                </vxe-column>
              </template>
              <vxe-column title="产品名称" field="sku_cn_title">
                <template #default="{ row }">
                  <VText :value="row.goods_sku?.sku_cn_title" :line="3"></VText>
                </template>
              </vxe-column>
            </vxe-table>
          </el-card>

          <el-form
            ref="formRef"
            :model="form"
            label-align="right"
            label-width="0"
            size="default"
            label-position="top"
            require-asterisk-position="right"
          >
            <el-card class="mb-2" shadow="never">
              <div>
                <span class="pictureTitle">人员信息</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="产品开发人员" required>
                    <select-personnel
                      v-model="form.developer_user"
                      placeholder="开发人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="运营人员" required>
                    <select-personnel
                      v-model="form.operators_user_ids"
                      :multiple="true"
                      placeholder="运营人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="图片处理人员">
                    <select-personnel
                      v-model="form.designer_user"
                      placeholder="图片处理人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="摄影人员">
                    <select-personnel
                      v-model="form.photography_user"
                      placeholder="摄影人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="编辑人员">
                    <select-personnel
                      v-model="form.edit_user"
                      placeholder="编辑人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="渲染人员">
                    <select-personnel
                      v-model="form.render_user"
                      placeholder="渲染人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="协助人员">
                    <select-personnel
                      v-model="form.assistance_user"
                      placeholder="协助人员"
                      disabled
                    ></select-personnel>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
            <el-card shadow="never">
              <div>
                <span class="pictureTitle">任务要求</span>
              </div>
              <div class="pb-2 text-[#999]">
                注：任务等级，环境电子基于销量进行选择A (1000以上) B (600-999) C (300-599)
                D (300以下)
              </div>
              <el-row :gutter="20">
                <el-col :span="16">
                  <el-form-item label="任务等级/类型">
                    <VGroup>
                      <el-select
                        v-model="form.task_priority"
                        class="!w-[160px]"
                        placeholder="请选择任务等级"
                        clearable
                        style="width: 140px"
                        disabled
                      >
                        <el-option
                          v-for="item in options['assignment.ImagesAssignment']?.[0]
                            .taskPriorityText"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                      <el-select
                        v-model="form.task_type"
                        placeholder="请选择任务类型"
                        multiple
                        clearable
                        style="width: 300px"
                        disabled
                      >
                        <el-option
                          v-for="item in options['assignment.ImagesAssignment']?.[0]
                            .taskTypeText"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </VGroup>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="任务优先级">
                    <el-select
                      class="w-full"
                      v-model="form.priority"
                      placeholder="请选择任务优先级"
                      clearable
                      disabled
                    >
                      <el-option
                        v-for="item in options['assignment.ImagesAssignment']?.[0]
                          .priorityText02"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="产品类型">
                    <el-select
                      class="w-full"
                      v-model="form.product_type"
                      placeholder="产品类型"
                      clearable
                      disabled
                    >
                      <el-option
                        v-for="item in options['assignment.ImagesAssignment']?.[0]
                          .productTypeText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="设计品牌">
                    <select-brand
                      class="w-full"
                      v-model="form.brand_id"
                      :multiple="true"
                      placeholder="设计品牌"
                      disabled
                    ></select-brand>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="图片数量">
                    <el-select
                      class="w-full"
                      v-model="form.image_total"
                      placeholder="产品类型"
                      clearable
                      disabled
                    >
                      <el-option
                        v-for="item in options['assignment.ImagesAssignment']?.[0]
                          .imageTotalText"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col class="relative" :span="8">
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="精铺：至少30天工期；精品：至少40天工期<br/>按各部门排期，可自行调整"
                    raw-content
                    placement="top"
                  >
                    <svg-icon
                      class="absolute left-24 top-1"
                      icon-class="hint_cover2"
                    ></svg-icon>
                  </el-tooltip>

                  <el-form-item label="预期完成时间">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.expected_time"
                      type="datetime"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      placeholder="请输入"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="目标套数（环境电子）">
                    <el-input
                      v-model="form.converted_quantity"
                      placeholder="请输入目标套数"
                      oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                      disabled
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="任务备注">
                    <el-input
                      v-model="form.task_remark"
                      :rows="2"
                      type="textarea"
                      placeholder="请输入"
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <div>
                <div style="font-weight: 700" class="text-base">附件</div>
                <template v-if="form.task_file?.length">
                  <FileUpload
                    v-model="form.task_file"
                    :isShowTip="false"
                    :progress="true"
                  ></FileUpload>
                </template>
                <div class="text-[#999999]" v-else>暂无附件</div>
              </div>
            </el-card>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="绩效标签查看" :name="2">
          <vxe-table
            :data="images_tag"
            style="width: 100%"
            :summary-method="getSummaries"
            show-summary
          >
            <vxe-column field="tag_type" title="标签类型" width="80">
              <template #default="{ row }">
                {{ row.images_tag?.tag_type == 1 ? "图片绩效" : "图片任务" }}
              </template>
            </vxe-column>
            <vxe-column field="tag_name" title="标签名称" width="120">
              <template #default="{ row }">
                {{ row.images_tag?.tag_name }}
              </template>
            </vxe-column>
            <vxe-column field="person" title="绩效人员" width="120">
              <template #default="{ row }">
                {{ row.username }}
              </template>
            </vxe-column>
            <vxe-column field="opearn" title="图片">
              <template #default="{ row }">
                <div class="flex">
                  <div v-for="(item, index) in row.img" :key="index">
                    <template v-if="item">
                      <VImageSrc
                        width="40"
                        height="40"
                        :src="item"
                        :preview="false"
                        @click="showImage(item, row.img)"
                      >
                      </VImageSrc>
                    </template>
                  </div>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="tag_count" title="数量" width="80">
              <template #default="{ row }">
                {{ row.tag_count || 1 }}
              </template>
            </vxe-column>
            <vxe-column field="score" title="单个标签分值" width="120"> </vxe-column>
            <!-- <el-table-column prop="" label="系数" width="120" v-if="is_coefficient">
              <template #default="{ row }">
                <template v-if="types == 'view'">{{ row.mode_three_coefficient }}</template>
                <el-select v-else v-model="row.mode_three_coefficient" collapse-tags placeholder="请选择" clearable
                  @change="changeCoefficient($event, row)" allow-create filterable>
                  <el-option v-for="item in options['assignment.ImagesTag']?.[0].coefficientText" :key="item.label"
                    :label="item.label" :value="item.label" />
                </el-select>
              </template>
            </el-table-column> -->
            <vxe-column field="total" title="总分数" width="80"></vxe-column>
          </vxe-table>
        </el-tab-pane>
        <el-tab-pane label="图片查看" :name="3">
          <el-tabs v-model="activeSKU" type="card">
            <el-tab-pane
              :label="i.sku"
              :name="i.custom_sku"
              v-for="(i, index) in imgList"
              :key="index"
            >
              <template #label>{{ i.sku || i.custom_sku }}</template>
              <template v-if="i.images_assignment_list.length">
                <div
                  class="mt-4"
                  v-for="item of i.images_assignment_list"
                  :key="item.custom_tag"
                  style="margin-bottom: 20px"
                >
                  <el-tabs
                    v-model="activeTab"
                    type="card"
                    class="demo-tabs"
                    @tab-click="handleClick"
                  >
                    <el-tab-pane
                      :label="item.custom_tag || '暂无标签名'"
                      :name="item.custom_tag"
                    >
                      <div
                        v-for="imageListItem of item.image_list"
                        :key="imageListItem.type"
                      >
                        <div
                          style="
                            padding: 15px 0;
                            text-align: center;
                            border-bottom: 1px solid #e4e7ed;
                            border-left: 1px solid #e4e7ed;
                            border-right: 1px solid #e4e7ed;
                          "
                        >
                          {{ imageListItem.label_type }}（{{
                            imageListItem.values.length
                          }}）
                        </div>
                        <ul
                          style="
                            padding: 16px 16px 16px 19px;
                            border: 1px solid #e4e7ed;
                            margin-top: -1px;
                            border-bottom-right-radius: 4px;
                            border-bottom-left-radius: 4px;
                            display: flex;
                            align-items: center;
                            flex-flow: wrap;
                          "
                        >
                          <li
                            style="margin-bottom: 10px"
                            class="listMr"
                            v-for="(imgChilder, idx) of imageListItem.values"
                            :key="idx"
                          >
                            <template v-if="imgChilder?.url">
                              <VImageSrc
                                :src="imgChilder.url"
                                :width="128"
                                :height="128"
                                :previewlist="photoSort(imgChilder, imageListItem.values)"
                              >
                              </VImageSrc>
                            </template>
                            <div class="overflow-line1" style="width: 128px">
                              {{ imgChilder.name }}
                            </div>
                          </li>
                        </ul>
                      </div>
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </template>
              <el-empty v-else :image-size="200" description="暂无图片" />
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="处理人备注" :name="4">
          <el-form :model="task_info" label-width="auto" label-position="top">
            <el-form-item label="处理人备注">
              <el-input
                v-model="task_info.handle_remark"
                type="textarea"
                placeholder="请输入处理人备注"
              />
            </el-form-item>
            <el-checkbox
              v-model="task_info.is_emphasis_remark"
              :true-label="1"
              :false-label="0"
              >是否重点备注</el-checkbox
            >
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <el-button v-if="activeName == 4" type="primary" @click="handleSaveRemark"
        >保存</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { reactive, ref, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { getOptions } from "@/api/index";
import {
  getImagesAssignmentDetail,
  getTaskTagList,
  getDetgetImagesail,
  editTaskInfo,
} from "../api/index.js";
import SelectBrand from "@/components/SelectBrand";
import VImageSrc from "@/components/Image/index.vue";
import { photoSort } from "@/utils/index";
import FileUpload from "@/components/FileUpload";

const visible = ref(false);
const formRef = ref(null);
const emits = defineEmits(["initForm"]);

const data = reactive({
  title: "查看",
  activeName: 1,
  form: {
    images_assignment_sku: [],
  },
  options: {},
  images_tag: [],
  task_info: {},
  activeSKU: "",
  imgList: [],
  activeTab: "",
  formData: {},
  load: false,
});
const {
  title,
  activeName,
  form,
  options,
  images_tag,
  task_info,
  activeSKU,
  imgList,
  activeTab,
  load,
} = toRefs(data);

// 下拉数据
const fetchOption = () => {
  getOptions({ name: ["assignment.ImagesAssignment", "assignment.ImagesTag"] }).then(
    (res) => {
      if (res.data["assignment.ImagesAssignment"][0].priorityText.length) {
        res.data["assignment.ImagesAssignment"][0].priorityText02 = res.data[
          "assignment.ImagesAssignment"
        ][0].priorityText.map((i) => {
          if (i.value == 1) {
            i.label = i.label + "(非常紧急)";
          } else if (i.value == 2) {
            i.label = i.label + "(紧急)";
          } else if (i.value == 3) {
            i.label = i.label + "(正常)";
          }
          return i;
        });
      }
      options.value = res.data;
    }
  );
};

fetchOption();

const arrAttributeList = computed(() => {
  if (form.value.images_assignment_sku.length > 0) {
    let data = form.value.images_assignment_sku[0];
    if (!data.goods_sku.sku_specification || data.goods_sku.sku_specification.length == 0)
      return [];
    return data.goods_sku.sku_specification.header;
  } else {
    return [];
  }
});

const open = async (task) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  task_info.value = task;
  changeTab(1);
  visible.value = true;
};

const close = () => {
  visible.value = false;
};
defineExpose({ open });

const changeTab = (val) => {
  console.log(val);
  if (val == 1) {
    getTaskDetail();
  } else if (val == 2) {
    getTaskTag();
  } else if (val == 3) {
    getImage();
  }
};

// 获取详情
const getTaskDetail = () => {
  getImagesAssignmentDetail({ task_id: task_info.value.task_id }).then((res) => {
    const data = res.data;
    // data.images_assignment_sku.forEach((item, index) => {
    //   item.images_assignment_list = item.images_assignment_list && item.images_assignment_list.length ? item.images_assignment_list.map(j => {
    //     if (j.image_list.length == 0) {
    //       j.image_list = initGalleryContents()
    //     } else {
    //       j.image_list = matchAndAdd(goods_spu_gallery.value[0].image_list, j.image_list)
    //       j.image_list = j.image_list.sort((a, b) => gallerySort(a.type) - gallerySort(b.type))
    //     }
    //     return j
    //   }) : initGallery(true)
    // })
    form.value = data;
  });
};

const getTaskTag = async () => {
  try {
    const res = await getTaskTagList({
      taskId: task_info.value.task_id,
    });
    images_tag.value = res.data.map((i) => {
      i.score = i.images_tag?.score;
      // if (is_coefficient.value) {
      //   i.total = Number((i.tag_count || 1) * i.mode_three_coefficient).toFixed(2)
      // } else {
      i.total = Number((i.tag_count || 1) * i.score).toFixed(2);
      // }
      return i;
    });
  } catch (e) {
    throw Error(e);
  }
};

const getImage = (taskId) => {
  getDetgetImagesail({ taskId: task_info.value.task_id }).then(({ data }) => {
    if (data.length > 0) {
      imgList.value = data;
      activeSKU.value = data[0].custom_sku;
      activeTab.value = data[0].images_assignment_list[0].custom_tag;
    }
  });
};

const handleClick = (tab, event) => {};

const handleSaveRemark = async () => {
  try {
    const res = await editTaskInfo({
      task_id: task_info.value.task_id,
      handle_remark: task_info.value.handle_remark,
      is_emphasis_remark: task_info.value.is_emphasis_remark,
    });
    ElMessage.success("操作成功");
    emits("initForm");
    close();
  } catch (e) {
    throw Error(e);
  }
};

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "汇总";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      const sum = values.reduce((prev, curr) => {
        const value = Number(curr);
        return !Number.isNaN(value) ? prev + value : prev;
      }, 0);
      sums[index] = Number(sum.toFixed(2));
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
</script>
<style lang="scss" scoped>
.pictureTitle {
  font-weight: bold;
  position: relative;
  padding-left: 6px;
  font-size: 16px;
  color: var(--base-sub-text-color);

  &::after {
    content: "";
    height: 14px;
    width: 2px;
    position: absolute;
    left: 0;
    top: 0;
    align-items: center;
    background-color: #3366f1;
  }
}
</style>
